import api from './utils/api'
import __config from './config/env'

App({
  api: api,
  globalData: {
    version: '2.8.18',
    thirdSession: null,
    wxUser: null,
    shoppingCartCount: 0, //购物车数量
    balanceIsEntrance: '0', //1开启充值
    theme: { //主题定义
      backgroundColor: 'white', //背景颜色,支持渐变色
      themeColor: 'orange', //主题颜色
      tabbarBackgroundColor: '#ffffff', //tabbar背景颜色
      tabbarColor: '#757A7F', //tabBar上的文字默认颜色
      tabbarSelectedColor: '#00D12D', //tabBar上的文字选中时的颜色
      tabbarBorderStyle: 'black', //tabBar上边框的颜色
      tabbarItem: [] //tabBar明细设置
    },
    expressSite: null,
    config: __config,
    addressComponent: {
      city: null,
      address: null,
      longitude: null,
      latitude: null
    },
    // 希望上门时间
    bookingTime: null
  },
  onLaunch: function () {
    //小程序平台检测新版本
    this.updateManager();
    // 获取充值模块状态
    this.loadBalanceConfig();
    this.doLogin();
    //设置全局样式
    this.setGlobalStyle();
    //获取购物车数量
    // if (wx.getStorageSync('third_session')) {
    //   this.shoppingCartCount();
    // }
  },
  setGlobalStyle() {
    wx.getSystemInfo({
      success: e => {
        this.globalData.StatusBar = e.statusBarHeight;
        let custom = wx.getMenuButtonBoundingClientRect();
        if (custom) {
          this.globalData.Custom = custom;
          this.globalData.CustomBar = custom.bottom + custom.top - e.statusBarHeight;
        } else {
          this.globalData.CustomBar = e.statusBarHeight + 50;
        }
      }
    })
    this.api.themeMobileGet().then(res => {
      var themeMobile = res.data;
      //定义默认配置
      var tabbarItem = [{
          index: 0,
          text: '首页',
          iconPath: "public/img/1-001.png",
          selectedIconPath: "public/img/1-002.png",
        },
        {
          index: 1,
          text: '服务',
          iconPath: "public/img/2-001.png",
          selectedIconPath: "public/img/2-002.png",
        },
        // {
        //   index: 2,
        //   text: '订单',
        //   iconPath: "public/img/3-001.png",
        //   selectedIconPath: "public/img/3-002.png",
        // },
        {
          index: 2,
          text: '我的',
          iconPath: "public/img/4-001.png",
          selectedIconPath: "public/img/4-002.png",
        }
      ];
      //将默认配置换成后台数据
      if (themeMobile) {
        this.globalData.theme.backgroundColor = themeMobile.backgroundColor;
        this.globalData.theme.themeColor = themeMobile.themeColor;
        this.globalData.theme.tabbarBackgroundColor = themeMobile.tabbarBackgroundColor;
        this.globalData.theme.tabbarColor = themeMobile.tabbarColor;
        this.globalData.theme.tabbarSelectedColor = themeMobile.tabbarSelectedColor;
        this.globalData.theme.tabbarBorderStyle = themeMobile.tabbarBorderStyle;
      }
      this.globalData.theme.tabbarItem = tabbarItem;
      if (themeMobile && themeMobile.tabbarItem && themeMobile.tabbarItem.info.length > 0) {
        var tabbarItemInfo = themeMobile.tabbarItem.info;
        tabbarItemInfo.forEach(function (item) {
          if (item.text) tabbarItem[item.index].text = item.text;
          if (item.iconPath) tabbarItem[item.index].iconPath = item.iconPath;
          if (item.selectedIconPath) tabbarItem[item.index].selectedIconPath = item.selectedIconPath;
        });
        this.globalData.theme.tabbarItem = tabbarItem;
      }
      this.setTabBar();
    })
  },
  //设置tabbar
  setTabBar() {
    var themeMobile = this.globalData.theme;
    if (themeMobile.tabbarBackgroundColor) {
      //动态设置 tabBar 的整体样式
      wx.setTabBarStyle({
        backgroundColor: themeMobile.tabbarBackgroundColor,
        color: themeMobile.tabbarColor,
        selectedColor: themeMobile.tabbarSelectedColor,
        borderStyle: themeMobile.tabbarBorderStyle
      });
      var tabbarItem = themeMobile.tabbarItem;
      tabbarItem.forEach(function (item) {
        //动态设置 tabBar 某一项的内容
        var iconPath = item.iconPath;
        var selectedIconPath = item.selectedIconPath;
        wx.setTabBarItem({
          index: item.index,
          text: item.text,
          iconPath: iconPath,
          selectedIconPath: selectedIconPath
        });
      });
    }
  },
  updateManager() {
    const updateManager = wx.getUpdateManager()
    updateManager.onUpdateReady(function () {
      wx.showModal({
        title: '更新提示',
        content: '新版本已经准备好，是否重启应用？',
        success(res) {
          if (res.confirm) {
            updateManager.applyUpdate()
          }
        }
      })
    })
  },
  //获取购物车数量
  shoppingCartCount() {
    // this.api.shoppingCartCount()
    //   .then(res => {
    //     let shoppingCartCount = res.data
    //     this.globalData.shoppingCartCount = shoppingCartCount + ''
    //     wx.setTabBarBadge({
    //       index: 2,
    //       text: this.globalData.shoppingCartCount + ''
    //     })
    //   })
  },
  //获取充值模块状态
  loadBalanceConfig() {
    this.api.balanceConfigGet()
      .then(res => {
        let data = res.data
        if (data) {
          this.globalData.balanceIsEntrance = data.isEntrance
          if (data.isEntrance === "1") {
            console.log("充值开启")
          } else {
            console.log("充值关闭")
          }
        }
      })
  },
  //初始化，供每个页面调用
  initPage: function () {
    var that = this;
    return new Promise(function (resolve, reject) {
      that.setTabBar();
      //小程序，每个页面都进行登录校验
      if (!wx.getStorageSync('third_session')) {
        //无thirdSession，进行登录
        that.doLogin().then(function (res) {
          resolve("success");
        });
      } else {
        wx.checkSession({
          success: function success() {
            //session_key 未过期，并且在本生命周期一直有效
            console.log('session_key 未过期');
            resolve("success");
          },
          fail: function fail() {
            // session_key 已经失效，需要重新执行登录流程
            console.log('session_key 已经失效');
            that.doLogin().then(function (res) {
              resolve("success");
            });
          }
        });
      }
    });
  },
  doLogin() {
    wx.showLoading({
      title: '登录中',
    })
    let that = this
    return new Promise(function (resolve, reject) {
      //微信小程序登录
      that.loginWxMa().then(function (res) {
        resolve("success");
      });
    });
  },
  //微信小程序登录
  loginWxMa: function loginWxMa() {
    var that = this;
    return new Promise(function (resolve, reject) {
      wx.login({
        success: function success(res) {
          if (res.code) {
            that.api.loginWxMa({
              jsCode: res.code
            }).then(function (res) {
              wx.hideLoading();
              var userInfo = res.data;
              wx.setStorageSync('third_session', userInfo.thirdSession);
              wx.setStorageSync('user_info', userInfo);
              // 获取购物车数量
              that.shoppingCartCount();
              resolve("success");
            });
          }
        }
      });
    });
  },
  //获取当前位置
  getCurrentLocation: function getCurrentLocation() {
    return new Promise(function (resolve, reject) {
      wx.getLocation({
        type: 'gcj02',
        success: function success(loc) {
          console.log(loc);
          resolve(loc);
        },
        fail: function fail(res) {
          reject(res);
        }
      });
    });
  },
  //判断获取当前位置权限
  checkLocation() {
    // 如果没有获取到地理位置，则需要获取当前的授权信息，判断是否有地理授权信息
    return new Promise(function (resolve, reject) {
      wx.getSetting({
        success: function success(res) {
          var status = res.authSetting;
          console.log(status);
          if (!status['scope.userLocation']) {
            // 未授权
            wx.authorize({
              scope: 'scope.userLocation',
              success: function success() { //1.1 允许授权
                console.log("允许授权");
                resolve("success");
              },
              fail: function fail() { //1.2 拒绝授权
                // 如果授权信息中没有地理位置的授权，则需要弹窗提示用户需要授权地理信息
                wx.showModal({
                  title: "是否授权当前位置",
                  content: "需要获取您的地理位置，请确认授权，否则地图功能将无法使用",
                  success: function success(tip) {
                    if (tip.confirm) {
                      // 如果用户同意授权地理信息，则打开授权设置页面，判断用户的操作
                      wx.openSetting({
                        success: function success(data) {
                          // 如果用户授权了地理信息在，则提示授权成功
                          if (data.authSetting['scope.userLocation'] === true) {
                            wx.showToast({
                              title: "授权成功",
                              icon: "success",
                              duration: 1000
                            });
                            resolve("success");
                          } else {
                            wx.showToast({
                              title: "授权失败",
                              icon: "none",
                              duration: 1000
                            });
                            reject();
                          }
                        }
                      });
                    } else {
                      resolve("success");
                    }
                  }
                });
              }
            });
          } else {
            resolve("success");
          }
        },
        fail: function fail(res) {
          wx.showToast({
            title: "调用授权窗口失败",
            icon: "none",
            duration: 1000
          });

          reject(res);
        }
      });
    });
  },
  //获取当前页面带参数的url
  getCurrentPageUrlWithArgs() {
    const pages = getCurrentPages()
    const currentPage = pages[pages.length - 1]
    const url = currentPage.route
    const options = currentPage.options
    let urlWithArgs = `/${url}?`
    for (let key in options) {
      const value = options[key]
      urlWithArgs += `${key}=${value}&`
    }
    urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1)
    return urlWithArgs
  }
})